package example.juc.test1;

public class SimpleWakeupDemo {

    private volatile static int product = 0; // 条件

    private static final Object lock = new Object();

    public static void main(String[] args) {

        Runnable consumer = new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {

                    if (product < 1) {
                        try {
                            System.out.println(Thread.currentThread().getName() + "不足");
                            System.out.println("before wait");
                            lock.wait();
                            System.out.println("after wait");
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                    }

                    product --;
                    System.out.println(Thread.currentThread().getName() + " = " + product);

                    lock.notifyAll();

                }
            }
        };

        Runnable productor = new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    try {
                        Thread.sleep(900);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    if (!(product < 1)) {
                        try {
                            System.out.println(Thread.currentThread().getName() + "已满");
                            System.out.println("before wait");
                            lock.wait();
                            System.out.println("after wait");
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                    }

                    product ++;
                    System.out.println(Thread.currentThread().getName() + " = " + product);

                    lock.notifyAll();
                }
            }
        };

        for (int i = 0; i < 10; i++) {
            new Thread(productor, "productor-"+i).start();
            new Thread(consumer, "consumer-"+i).start();
        }

    }


}
